package com.flyox.game.fivetiger.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.plaf.metal.MetalComboBoxIcon;

/**
 * 组合控件 包括 两个按钮，一个弹出菜单
 * 
 * @author sunwei
 * 
 */
public class ComboButton extends javax.swing.JPanel {

	private static final long serialVersionUID = 1757110216438224764L;
	private JButton mainButton;
	private JButton listButton;
	protected JPopupMenu popMenu = new JPopupMenu();
	private JMenuItem[] items;

	public ComboButton() {
		super();
		initGUI();
	}

	public void initAction(JMenuItem[] items) {
		this.items = items;
		mainButton.setAction(items[0].getAction());
		for (int i = 0; i < items.length; i++) {
			items[i].setBackground(new java.awt.Color(252, 245, 76));
			popMenu.add(items[i]);
		}
		popMenu.setBackground(new java.awt.Color(252, 245, 76));
	}

	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(100, 22));
			this.setLayout(null);
			{
				mainButton = new JButton();
				this.add(mainButton);
				mainButton.setBounds(0, 0, 82, 22);
				mainButton.setSize(82, 22);
				mainButton.setBackground(new java.awt.Color(252, 245, 76));
			}
			{
				listButton = new JButton(new MetalComboBoxIcon());
				this.add(listButton);
				listButton.setBounds(82, 0, 18, 22);
				listButton.setBackground(new java.awt.Color(252, 245, 76));
				listButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						popMenu.show(mainButton, 0, mainButton.getHeight());
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateMainButton(JMenuItem item) {
		mainButton.setText(item.getText());
		mainButton.setAction(item.getAction());
	}

	public void refreshButtons() {
		for (int i = 0; i < items.length; i++) {
			if (!mainButton.getText().equals(items[i].getText())) {
				continue;
			}
			if (items[i].isEnabled()) {
				mainButton.setEnabled(true);
			} else {
				mainButton.setEnabled(false);
			}
		}

	}
}
